package com.myhome.money.base.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author 许路路
 */
public class WebService {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8111));
        //设置非阻塞
        socketChannel.configureBlocking(false);

        Selector selector = Selector.open();

        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        ByteBuffer readBuff = ByteBuffer.allocate(1024);
        ByteBuffer writeBuff = ByteBuffer.allocate(128);
        writeBuff.put("received".getBytes());
        writeBuff.flip();

        while (true) {
            Set<SelectionKey> keySet = selector.selectedKeys();
            Iterator<SelectionKey> iterable = keySet.iterator();

            while (iterable.hasNext()) {
                SelectionKey selectionKey = iterable.next();
                iterable.remove();

                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChan = socketChannel.accept();
                    socketChan.configureBlocking(false);
                    socketChan.register(selector, SelectionKey.OP_READ);

                } else if (selectionKey.isReadable()) {
                    SocketChannel socketCh = (SocketChannel) selectionKey.channel();
                    readBuff.clear();
                    socketCh.read(readBuff);

                    readBuff.flip();
                    System.out.println("received:" + new String(readBuff.array()));
                    selectionKey.interestOps(SelectionKey.OP_WRITE);

                } else if (selectionKey.isWritable()) {
                    writeBuff.rewind();
                    SocketChannel socketCha = (SocketChannel) selectionKey.channel();
                    socketCha.write(writeBuff);
                    selectionKey.interestOps(SelectionKey.OP_READ);
                }
            }
        }
    }
}
